#! /usr/bin/python

"""
A command-line client for OpenSocial RESTful APIs.

Takes arguments of requests to run against the container, and runs them,
printing results.

If none are given, runs a standard request to find john.doe's friends.

(Will become better-featured soon.)
"""

# TODO(dbentley): document usage thoroughly

import getopt
import sys

# TODO(dbentley): this is a hacky way to import the library,
# but it should help get this example code working without
# installation for easy showing off, and since this isn't production
# code, it should be alright for now.
import os
# We take __file__, which is the path to this file.
# We then turn it into an absolute path.
# Then, and this depends on the directory structure we have (i.e.
# We are in foo/examples/clclient.py, and the library code is in
# foo/opensocialclient/*.py ), we take dirname once to get foo/examples,
# and a second time gives us foo.  Foo, whatever the name of the svn client
# directory is, is appended to the python path.
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from opensocialclient import client


DEFAULT_REQUEST = 'people/john.doe/@friends'
DEFAULT_USER = 'john.doe'
SERVER_FLAG_NAME = 'server'
SERVER_FLAG_NAME_WITH_DASHES = '--' + SERVER_FLAG_NAME

def Fetch(c, user):
  """Fetch user's friends.

  Params:
    c: an opensocialcient.client.Client
    user: str, the user whose friends to fetch we ought

  Side effects:
    Prints out the requests and their response to stdout.
  """
  print 'FETCHING FRIENDS OF %s:' % user
  response = c.GetFriends(user)
  print response


def main(args):
  (settings, remaining_args) = getopt.getopt(args, '', ['server='])
  # TODO(dbentley): right now, specifying the server is very brittle.
  # You have to prefix with http://, or else you get weird connection errors.
  settings_map = dict(settings)
  server_path = settings_map.get(SERVER_FLAG_NAME_WITH_DASHES,
                                 client.DEFAULT_SERVER)
  c = client.Client(server_path)
  if remaining_args:
    for arg in remaining_args:
      Fetch(c, arg)
  else:
    Fetch(c, DEFAULT_USER)


if __name__ == '__main__':
  main(sys.argv[1:]) # don't deal with the name of the binary
